package com.iamteer.a_filter_hello;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 过滤器测试
 * @author Chuck
 *
 */
public class HelloFilter implements Filter {

	// 创建实例
	public HelloFilter() {
		System.out.println("0. 创建过滤器实例");
	}
	
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		System.out.println("1. 执行过滤器初始化方法");
		// 获取过滤器在web.xml 中配置的初始化参数
		String encoding = arg0.getInitParameter("encoding");
		System.out.println(encoding);
		
		// 获取过滤器在 web.xml 中配置的初始化参数的名称
		Enumeration<String> enums = arg0.getInitParameterNames();
		while (enums.hasMoreElements()) {
			// 获取所有参数名称：encoding、path
			String name = (String) enums.nextElement();
			// 获取对应的值
			String value = arg0.getInitParameter(name);
			System.out.println(name + "\t" + value);
		}
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		System.out.println("2.  执行过滤器业务处理方法");
		// 放行，到 servlet
		arg2.doFilter(arg0, arg1);
		//回来
		System.out.println("4. servlet 处理完成，又回到过滤器");
	}

	@Override
	public void destroy() {
		System.out.println("6.  销毁过滤器实例");
	}
}
